# Copyright 2018 Maco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import logging
import logzero
from blockchain.config import config

ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))

LOG_PATH = os.path.join(ROOT_PATH, 'log', 'server.log')
if not os.path.exists(os.path.dirname(LOG_PATH)):
    os.makedirs(os.path.dirname(LOG_PATH))
__all__ = ['setting']


def create_logger():
    '''create logger'''
    fmt = '%(color)s[%(asctime)s] %(name)s <%(levelname)s>%(end_color)s : %(message)s'
    formatter = logzero.LogFormatter(fmt=fmt)
    logger = logzero.setup_logger(
        name='Server.Web',
        logfile=LOG_PATH,
        level=logging.DEBUG,
        formatter=formatter,
        backupCount=4,
        maxBytes=1024 * 1024 * 200)
    return logger

LOG = create_logger()


def _log(handler):
    if handler.get_status() < 400:
        log_method = LOG.info
    elif handler.get_status() < 500:
        log_method = LOG.warning
    else:
        log_method = LOG.error
    req_time = 1000.0 * handler.request.request_time()
    log_method('%d %s %.2fms', handler.get_status(),
               handler._request_summary(), req_time)


def setting():
    return dict(
        template_path=os.path.join(ROOT_PATH, 'templates'),
        static_path=os.path.join(ROOT_PATH, 'static'),
        cookie_secret='w61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=',
        xsrf_cookies=False,
        log_function=_log,
        debug=config.get_bool_opt('base', '_debug', False),
        autoreload=config.get_bool_opt('base', '_autoreload', False)
    )
